package com.weayer.remote;

import com.weayer.constant.AmapConfigConstants;
import com.weayer.dto.ResponseResult;
import com.weayer.response.TrackResponse;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @description: 调用轨迹管理Client
 * @author: Weayer
 **/
@Service
public class MapTrackClient {
    @Value("${amap.key}")
    private String amapKey;
    @Value("${amap.sid}")
    private String amapSid;
    @Autowired
    private RestTemplate restTemplate;

    /**
     * @Description: 创建轨迹
     * @Param: [tid]
     * @return: com.weayer.dto.ResponseResult<com.weayer.response.TrackResponse>
     **/
    public ResponseResult<TrackResponse> add(String tid){
        // 1. 组装url:
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append(AmapConfigConstants.TRACK_ADD_URL_PREFIX);
        urlBuilder.append("?");
        urlBuilder.append("key=" + amapKey);
        urlBuilder.append("&");
        urlBuilder.append("sid=" + amapSid);
        urlBuilder.append("&");
        urlBuilder.append("tid=" + tid);
        // 2. 调用高德地图api
        ResponseEntity<String> serviceEntity = restTemplate.postForEntity(urlBuilder.toString(), null, String.class);
        // 3. 解析接口
        return parseServiceEntity(serviceEntity.getBody());
    }
    public ResponseResult<TrackResponse> parseServiceEntity(String serviceString){
        /**
         * {
         *     "code": 1,
         *     "message": "success",
         *     "data": {
         *         "trname": "",
         *         "trid": "20"
         *     }
         * }
         **/
        JSONObject result = JSONObject.fromObject(serviceString);
        JSONObject data = result.getJSONObject("data");
        TrackResponse trackResponse = new TrackResponse();
        trackResponse.setTrid(data.getString("trid"));
        String trname = "";
        if(data.has("trname")){
            trname = data.getString("trname");
        }
        trackResponse.setTrname(trname);
        return ResponseResult.success(trackResponse);
    }
}
